/**
 * MessageView.js
 * 
 * 负责渲染和管理聊天消息视图，包括用户消息、AI消息、工具调用卡片等。
 */

(function() {

    'use strict';
    class MessageView {
        constructor() {
            this.container = document.getElementById('messages-container');
            this.welcomeMsg = document.querySelector('.welcome-message');
        }

        /** 显示用户或AI消息 */
        addMessage(role, content, attachments = []) {
            this._removeWelcome();
            const div = document.createElement('div');
            div.className = `msg msg-${role}`;
            
            // 简单的 HTML 转义防止注入，实际项目可用 textContent
            const contentDiv = document.createElement('div');
            contentDiv.className = 'msg-content';
            contentDiv.textContent = content;
            div.appendChild(contentDiv);

           // 🟢 修复 1: 补全附件渲染逻辑
            if (attachments && attachments.length > 0) {
                const attContainer = document.createElement('div');
                attContainer.className = 'msg-attachments'; // 对应 chat.css
                
                attachments.forEach(att => {
                    const badge = document.createElement('span');
                    badge.className = 'attachment-badge'; // 对应 chat.css
                    badge.innerHTML = `<span class="codicon codicon-file"></span> ${att.name}`;
                    badge.title = att.path;
                    attContainer.appendChild(badge);
                });
                div.appendChild(attContainer);
            }
            
            this.container.appendChild(div);
            this._scrollToBottom();
            return div; // 返回引用方便后续操作
        }
        

        /** 流式追加 */
        appendToMessage(messageId, chunk) {
            let msgEl = this.container.querySelector(`[data-id="${messageId}"]`);
            if (!msgEl) {
                msgEl = this.addMessage('assistant', '');
                msgEl.setAttribute('data-id', messageId);
            }
            msgEl.querySelector('.msg-content').textContent += chunk;
            this._scrollToBottom();
        }

        /** 工具调用卡片 */
        addToolCall(toolName, status = 'running') {
            this._removeWelcome();
            const card = document.createElement('div');
            card.className = 'tool-call-card';
            card.setAttribute('data-status', status);
            card.innerHTML = `
                <div class="tool-header">
                    <span class="codicon codicon-tools"></span>
                    <span>Calling: ${toolName}...</span>
                </div>
            `;
            this.container.appendChild(card);
            this._scrollToBottom();
            return card;
        }

        updateToolCall(cardElement, result) {
            if (!cardElement) return;
            const status = result.success ? 'success' : 'error';
            cardElement.setAttribute('data-status', status);
            cardElement.querySelector('.tool-header span:last-child').textContent = 
                `Tool ${result.success ? 'Completed' : 'Failed'}`;
        }

        // 新增工具确认卡片 UI（作为消息插入到消息流中）
        addToolConfirmationMessage(toolCall, messageId, onDecide) {
            this._removeWelcome();
            const wrapper = document.createElement('div');
            wrapper.className = 'msg msg-system tool-confirmation';
            wrapper.setAttribute('data-id', messageId);

            // 获取工具名称和命令内容
            const toolName = toolCall.name || 'Unknown Tool';
            const command = toolCall.args?.command || JSON.stringify(toolCall.args || {});

            wrapper.innerHTML = `
                <div class="confirmation-card">
                    <div class="confirmation-title">
                        <span class="codicon codicon-warning"></span> 
                        <span>AI 请求执行工具: <strong>${this._escapeHtml(toolName)}</strong></span>
                    </div>
                    <div class="confirmation-info">
                        <div class="info-label">参数:</div>
                        <div class="info-value"><code>${this._escapeHtml(command)}</code></div>
                    </div>
                    <div class="confirmation-buttons">
                        <vscode-button appearance="secondary" class="btn-reject">
                            <span class="codicon codicon-close"></span> 拒绝
                        </vscode-button>
                        <vscode-button appearance="primary" class="btn-approve">
                            <span class="codicon codicon-check"></span> 允许执行
                        </vscode-button>
                    </div>
                </div>
            `;

            this.container.appendChild(wrapper);

            // 等待 Web Components 渲染完成后再绑定事件
            requestAnimationFrame(() => {
                const rejectBtn = wrapper.querySelector('.btn-reject');
                const approveBtn = wrapper.querySelector('.btn-approve');
                
                if (rejectBtn) {
                    rejectBtn.onclick = () => {
                        console.log('[MessageView] Tool confirmation: rejected');
                        onDecide(false);
                    };
                }
                
                if (approveBtn) {
                    approveBtn.onclick = () => {
                        console.log('[MessageView] Tool confirmation: approved');
                        onDecide(true);
                    };
                }
            });

            this._scrollToBottom();
        }

        // 更新确认卡片状态（点击后）
        updateConfirmationStatus(messageId, approved) {
            const wrapper = this.container.querySelector(`[data-id="${messageId}"]`);
            if (!wrapper) return;

            const statusIcon = approved ? 'check' : 'close';
            const statusText = approved ? '已允许执行' : '已拒绝执行';
            const statusClass = approved ? 'approved' : 'rejected';
            
            wrapper.innerHTML = `
                <div class="confirmation-result ${statusClass}">
                    <span class="codicon codicon-${statusIcon}"></span>
                    <span>${statusText}</span>
                </div>
            `;
        }

        clear() {
            this.container.innerHTML = '';
            this._scrollToBottom();
        }

        /**
         * 恢复聊天历史记录
         * @param {Array} messages - 消息历史数组
         */
        restoreHistory(messages) {
            if (!messages || messages.length === 0) return;

            this._removeWelcome();
            this.container.innerHTML = ''; // 清空当前内容

            messages.forEach(msg => {
                this._renderMessage(msg);
            });

            this._scrollToBottom();
        }

        /**
         * 渲染单条消息（用于历史恢复）
         * @private
         */
        _renderMessage(msg) {
            switch (msg.type) {
                case 'user':
                    this.addMessage('user', msg.content, msg.attachments);
                    break;

                case 'assistant':
                    const assistantMsg = this.addMessage('assistant', msg.content);
                    if (msg.id) {
                        assistantMsg.setAttribute('data-id', msg.id);
                    }
                    // 如果是流式消息状态，移除加载动画
                    if (msg.status === 'sent') {
                        assistantMsg.classList.remove('loading');
                    }
                    break;

                case 'tool-call':
                    const toolName = msg.content.replace('Calling tool: ', '');
                    const status = msg.toolResult?.success ? 'success' : 
                                   msg.toolResult?.error ? 'error' : 'running';
                    const card = this.addToolCall(toolName, status);
                    if (msg.id) {
                        card.setAttribute('data-id', msg.id);
                    }
                    break;

                case 'tool-result':
                    // 工具结果通常已经在 tool-call 中显示，这里可以跳过
                    // 或者根据需要显示额外的结果信息
                    break;

                default:
                    console.warn('[MessageView] Unknown message type:', msg.type);
            }
        }

        _removeWelcome() {
            if (this.welcomeMsg) this.welcomeMsg.style.display = 'none';
        }

        _scrollToBottom() {
            this.container.parentElement.scrollTop = this.container.parentElement.scrollHeight;
        }

        /**
         * HTML 转义，防止 XSS 攻击
         * @private
         */
        _escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    }

    window.MessageView = MessageView;
})();